﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using DotNetStar.TheKing.Domain;
using DotNetStar.TheKing.Infrastructure;
using DotNetStar.TheKing.Models;
using DotNetStar.TheKing.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace DotNetStar.TheKing.Web.Pages
{
    public class DetailModel : PageModel
    {
        private ContentService _contentService;
        private UserService _userService;
        
        public Domain.Content ContentModel { get; set; }

        /// <summary>
        /// 热门帖子
        /// </summary>
        public IEnumerable<Domain.Content> HotContent { get; set; }

        public IEnumerable<Domain.Content> UserContents { get; set; }

        public IEnumerable<Tuple<Domain.User, UserContentPayHistory>> PaidUsers { get; set; }

        public IEnumerable<ContentComment> Comments { get; set; }

        /// <summary>
        /// 是否点过赞
        /// </summary>
        public bool HasLike { get; set; }

        /// <summary>
        /// 是否需要付费才能阅读
        /// </summary>
        public bool NeedPay { get; set; }
        
        public DetailModel(ContentService contentService,UserService userService)
        {
            _contentService = contentService;
            _userService = userService;
        }

        public async Task<IActionResult> OnGetAsync(int id)
        {
            var content = await _contentService.GetContentAsync(id);
            if (content == null)
            {
                return RedirectToPage("/Error",new { message="帖子不存在或已被删除" });
            }
            
            if((content.IsSecret || content.Status!= ContentStatus.Normal) && content.Author.Id != User.Identity.UserId())
            {
                return RedirectToPage("/Unauthorize");
            }
            this.ContentModel = content;
            
            this.Comments = await _contentService.GetCommentsAsync(id);

            if (User.Identity.IsAuthenticated)
            {
                this.HasLike = (await _contentService.IsContentHasLikeAsync(content.Id, User.Identity.UserId())).hasLike;
            }
            return Page();



            
        }
        
        public async Task<IActionResult> OnPostCommentAsync(string body,long contentId)
        {
            var result = await _contentService.CreateCommentAsync(body, contentId, User.Identity.UserId());
            if (result.IsSucceed)
            {
                return StatusCode(200);
            }
            return StatusCode(400, result.Errors);
        }

        /// <summary>
        /// 点赞操作
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> OnPostLikeAsync(long id)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return StatusCode((int)HttpStatusCode.Unauthorized, "登录后可点赞");
            }
            var (likeNum, hasLike) = await _contentService.OperateLikeAsync(id, User.Identity.UserId());

            return StatusCode(200, new { likeNum, hasLike});
        }

        /// <summary>
        /// 付费阅读
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IActionResult> OnPostPayAsync(long id)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return StatusCode((int)HttpStatusCode.Unauthorized, "你还没有登录");
            }

            try
            {
                await _contentService.PayContentAsync(id, User.Identity.UserId());
                return StatusCode(200);
            }
            catch (Exception ex)
            {
                return StatusCode(400,ex.Message);
            }
        }
        [Authorize]
        public async Task<IActionResult> OnPostDeleteAsync(int contentId)
        {
            try
            {
                await _contentService.DeleteContentAsync(contentId, User.Identity.UserId());
               
                return StatusCode(200);

            }
            catch (ContentNotFoundException ex)
            {
                return StatusCode(404, ex.Message);
            }
            catch (UnauthorizedAccessException ex)
            {
                return StatusCode(403, ex.Message);
            }
        }

        [Authorize]
        public async Task<IActionResult> OnPostSetBestAnswerAsync(long contentId,Guid commentId)
        {
            try
            {
                var result= await _contentService.SetAskBestCommentAsync(contentId,commentId, User.Identity.UserId());
                if (result.IsSucceed)
                {
                    return StatusCode(200);
                }
                return StatusCode(400, result.Errors);
            }
            catch (ContentNotFoundException ex)
            {
                return StatusCode(404, ex.Message);
            }
            catch (UnauthorizedAccessException ex)
            {
                return StatusCode(403, ex.Message);
            }
        }

    }
}